import os
import sys
import thread
import logging

from socf import conf
from socf.server import remote
from socf.server import discovery

from socf.test import conf_test
from socf.test import dbus_test

def __setupLogging():
    logger = logging.getLogger("socf")
    logger.setLevel(logging.DEBUG)
    con = logging.StreamHandler();
    con.setLevel(logging.DEBUG)
    formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
    con.setFormatter(formatter)
    logger.addHandler(con)
    
def __startRemoteProvider(provider):
    provider.start()
    
def __init_services(configContext):
    #get logger
    logger = logging.getLogger("socf")
    
    #discover services
    discoveryProvider1 = discovery.UserDefinedDiscoveryProvider(configContext)
    discoveryProvider2 = discovery.HALDiscoveryProvider(configContext)
    devices = discoveryProvider1.getDiscoveredDevices()
    devices.extend(discoveryProvider2.getDiscoveredDevices())
    
    #retrieve drivers
    ddMappings = conf.DeviceDriverMappings(configContext) 
    drivers = []
    for device in devices:
        logger.info("Device ID: %s" % device[2])
        try:
            driver = ddMappings.getDriverInfoByDevice(device)[0]
            drivers.append(driver)
        except Exception, ex:
            logger.error("Error in initalising the driver for device " + str(device) + " - " + str(ex))
    
    logger.info("Drivers:-\n%s\n" % drivers)
    
    #retrieve services
    dsMappings = conf.DriverServiceMappings(configContext)
    serviceRegistry = conf.ServiceRegistry(configContext)
    serviceInfoList = []
    dd = []
    for driver in drivers:        
        serviceType = dsMappings.getServiceTypeByDriver(driver.__class__.__name__)
        serviceModule = serviceRegistry.getServiceInfoByType(serviceType)[0]
        serviceModule.setDriver(driver)        
        serviceInfoList.append((serviceType,  serviceModule)) 

    #add the discovery service
    discoveryServiceType = 1000
    serviceModule = serviceRegistry.getServiceInfoByType(discoveryServiceType)[0]
    serviceModule.setDriver(None)
    serviceInfoList.append((discoveryServiceType,  serviceModule))
    
    #deploy services
    remoteProvider = remote.RemoteObjectSkeletonProvider.createProvider(configContext,  "dbus")
    for serviceInfo in serviceInfoList:
        remoteProvider.deploy(serviceInfo[0],  serviceInfo[1])
    
    logger.info("Services:-\n%s\n" % serviceInfoList)
    
    #start serving
    thread.start_new_thread(__startRemoteProvider,  (remoteProvider, ))
    
def main(argv):
    configContext = conf.ConfigurationContext(os.path.join(os.getcwd(),  "conf"))

    # initialise logging  
    __setupLogging()
    logger = logging.getLogger("socf")
    logger.info("socf server starting...")
    
    __init_services(configContext)
    
    #infinite loop to keep the server running
    while 1==1:
        text = raw_input(">>")
        if  text == "q":
            print "Quit."
            sys.exit()

if __name__ == "__main__":
    main(sys.argv)

